package com.yc.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.DefaultResponse;
import org.springframework.cloud.client.loadbalancer.EmptyResponse;
import org.springframework.cloud.client.loadbalancer.Request;
import org.springframework.cloud.client.loadbalancer.Response;
import org.springframework.cloud.loadbalancer.core.ReactorServiceInstanceLoadBalancer;
import org.springframework.cloud.loadbalancer.core.ServiceInstanceListSupplier;
import reactor.core.publisher.Mono;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Random;

/**
 * @author zwei
 * @create 2024-09-06 17:36
 */
@Slf4j
public class OddEvenTrafficLoadBalancer implements ReactorServiceInstanceLoadBalancer {
    //服务实例清单提供器
    private final ServiceInstanceListSupplier serviceInstanceListSupplier;
    public OddEvenTrafficLoadBalancer(ServiceInstanceListSupplier serviceInstanceListSupplier) {
        this.serviceInstanceListSupplier = serviceInstanceListSupplier;
    }


    @Override
    public Mono<Response<ServiceInstance>> choose(Request request) {
        return serviceInstanceListSupplier.get(request).next().map(serviceInstances -> {
            return getInstanceResponse(serviceInstances);
        });
    }

    //自定义单双号负载均衡
    private Response<ServiceInstance>getInstanceResponse(List<ServiceInstance>instances){
        log.info("自定义负载均衡");
        if (instances.isEmpty()){
            return new EmptyResponse();
        }
        int size=instances.size();
        if (size==1){
            return new DefaultResponse(instances.get(0));
        }
        int date= LocalDateTime.now().getDayOfMonth();  //取当前为多少号
        Random random=new Random();
        int randowNum;
        if (date%2==0){         //偶数天
            do{
                randowNum=random.nextInt(size);     //生成0到n之间的随机数
            }while (randowNum%2!=0);        //确保是奇数
            return new DefaultResponse(instances.get(randowNum));
        }else {
            do {
                randowNum=random.nextInt(size);     //生成0到n之间的随机数
            }while (randowNum%2==0);
            return new DefaultResponse(instances.get(randowNum));
        }
    }
}
